<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
require_once("recaptcha-php/include.php");

/**
 * Signup
 * 
 * Signup for an ESCAPE account.
 */
class escape_repositoryui_action_Signup extends escape_repositoryui_Action
{
	public function handleRequest()
	{
		session_start();
		
		/* @var $repository escape_repository_Repository */
		$repository =& $this->requestAttributes['repository'];
		/* @var $repositoryUi escape_repositoryui_RepositoryUi */
		$repositoryUi =& $this->requestAttributes['repositoryUi'];
		
		// check if signup is enabled
		if(!$repository->config['localauthn_enabled'] || !$repository->config['signup_enabled'])
		{
			// signup is disabled
			$repositoryUi->displayErrorPage('Signup is disabled.');
			return null;
		}
		
		$returnUrl = $repository->config['server_url'];
		if(isset($_REQUEST['return_url']))
		{
			$returnUrl = $_REQUEST['return_url'];
		}
		$this->requestAttributes['returnUrl'] = $returnUrl;
		
		
		$verb = null;
		if(isset($_REQUEST['verb']))
		{
			$verb = $_REQUEST['verb'];
		}
		
		$userId = null;
		if(isset($_REQUEST['userid']))
		{
			$userId = $_REQUEST['userid'];
		}
		$this->requestAttributes['userId'] = $userId;
	
		$fullname = null;
		if(isset($_REQUEST['fullname']))
		{
			$fullname = $_REQUEST['fullname'];
		}
		else if(isset($_SESSION['openid_firstname']) && isset($_SESSION['openid_lastname']))
		{
			$fullname = $_SESSION['openid_firstname'] . ' ' . $_SESSION['openid_lastname'];
		}
		$this->requestAttributes['fullname'] = $fullname;
		
		$email = null;
		if(isset($_REQUEST['email']))
		{
			$email = $_REQUEST['email'];
		}
		else if(isset($_SESSION['openid_email']))
		{
			$email = $_SESSION['openid_email'];
		}
		$this->requestAttributes['email'] = $email;
		
		$organization = null;
		if(isset($_REQUEST['organization']))
		{
			$organization = $_REQUEST['organization'];
		}
		$this->requestAttributes['organization'] = $organization;

		$dai = null;
		if(isset($_REQUEST['dai']))
		{
			$dai = $_REQUEST['dai'];
		}
		$this->requestAttributes['dai'] = $dai;
		
		$password = null;
		if(isset($_REQUEST['password']))
		{
			$password = $_REQUEST['password'];
		}
		
		$recaptchaError = null;
		$errorMessages = array();
		
		if($verb === 'create')
		{
			if($userId == '')
			{
				$errorMessages[] = 'Please provide a user ID';
			}
			if($fullname == '')
			{
				$errorMessages[] = 'Please provide your full name';
			}
			if($email == '')
			{
				$errorMessages[] = 'Please provide a email address';
			}
			if($password == '' && !isset($_SESSION['openid_identifier']))
			{
				$errorMessages[] = 'Please provide a password';
			}
	
	
			$recaptchaResponse = recaptcha_check_answer($repository->config['recaptcha_private_key'],
												$_SERVER["REMOTE_ADDR"],
												$_POST["recaptcha_challenge_field"],
												$_POST["recaptcha_response_field"]);
			
			if(!$recaptchaResponse->is_valid)
			{
				$recaptchaError = $recaptchaResponse->error;
				$errorMessages[] = 'CAPTCHA confirmation failed';
			}
			
			
			if(count($errorMessages) === 0)
			{
				//TODO: keep in sync with AdminCreateUser.php, Account.php, AdminEditUser.php, ResetPassword.php or move to shared function
				if(strlen($userId) > 32)
				{
					$errorMessages[] = 'User ID is too long, please use at most 32 characters';
				}
				if(strlen($userId) < 4)
				{
					$errorMessages[] = 'User ID is too short, please use at least 4 characters';
				}
				if(strlen($fullname) > 250)
				{
					$errorMessages[] = 'Full name is too long, please use at most 250 characters';
				}
				if(!isset($_SESSION['openid_identifier']) || strlen($password) > 0)
				{
					if(strlen($password) > 32)
					{
						$errorMessages[] = 'Password is too long, please use at most 32 characters';
					}
					if(strlen($password) < 4)
					{
						$errorMessages[] = 'Password is too short, please use at least 4 characters';
					}
				}
				if(strlen($email) > 250)
				{
					$errorMessages[] = 'Email address is too long, please use at most 250 characters';
				}
	
				if(!preg_match('~^(([a-z0-9])|-|\.|_)+$~', $userId))
				{
					$errorMessages[] = "Invalid user ID, please use only lowercase letters, numbers, '-', '.' or '_'";
				}
				if(!preg_match('~^[^@]+@[^.]+\..+~', $email))
				{
					$errorMessages[] = 'Invalid email address';
				}
			}
			
			if(count($errorMessages) === 0)
			{
				$userUri = $repository->convertUserObjectIdToObjectUri($userId);
				
				$existingUser = null;
				try
				{
					$existingUser = $repository->getUserByUri($userUri);
				}
				catch(escape_repository_exception_NotFound $exception)
				{
					//ignore
				}
				
				if($existingUser)
				{
					$errorMessages[] = 'The user ID \'' . htmlspecialchars($userId) . '\' is already in use, please choose another user ID';
				}
				else
				{
					$user = $repository->createUser($userUri);
					if($user)
					{
						$user->setName($fullname);
						$user->setMbox($email);
						if($_SESSION['openid_identifier'])
						{
							$user->addOpenId($_SESSION['openid_identifier']);
						}
						if($user->getOrganization() != '')
						{
							$user->setOrganization($organization);
						}
						if($user->getDai() != '')
						{
							$user->setDai($dai);
						}
						if($password !== null)
						{
							$user->setPassword($password);
						}
						
						$_SESSION['user_uri'] = $user->getUri();
						
						header("Location: " . $returnUrl);
						
						return null;
					}
				}
			}
		}
		
		$this->requestAttributes['errorMessages'] =& $errorMessages;
		$this->requestAttributes['recaptchaError'] = $recaptchaError;
		
		return 'SignupForm';
	}
}